/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lucava.widget.uspeed;

import java.awt.Dimension;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;

/**
 * 
 * @author glenn
 */
public class UspeedEditor extends JPanel implements DocumentListener {

	private JTextPane textPane;

	/**
	 * Types de modification appliquée au textPane
	 */
	private static enum Mode {

		INSERT, COLORATION
	};

	/**
	 * Type de modification courante
	 */
	private Mode mode = Mode.INSERT;

	public UspeedEditor() {

		this.initComponents();
	}

	public String getText() {
		return this.textPane.getText();
	}

	public void setText(String aText) {
		this.textPane.setText(aText);
	}

	private void initComponents() {
		textPane = new JTextPane();
		textPane.setPreferredSize(new Dimension(400, 700));

		// JScrollPane editorScrollPane = new JScrollPane(textPane);
		// editorScrollPane.setVerticalScrollBarPolicy(
		// JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		// editorScrollPane.setPreferredSize(new Dimension(600, 400));
		textPane.getDocument().addDocumentListener(this);

		this.add(textPane);
	}

	// Listener methods

	@Override
	public void changedUpdate(DocumentEvent ev) {
		onContentChanged(ev);
	}

	@Override
	public void removeUpdate(DocumentEvent ev) {
		onContentChanged(ev);
	}

	@Override
	public void insertUpdate(DocumentEvent ev) {
		onContentChanged(ev);
	}

	/**
	 * A chaque modification du textPane
	 * 
	 * @param ev
	 */
	private void onContentChanged(DocumentEvent ev) {
		if (mode != Mode.INSERT) {
			return;
		}

		int pos = ev.getOffset();
		String content = null;
		try {
			content = textPane.getText(0, pos + 1);
		} catch (BadLocationException e) {
			e.printStackTrace();
		}

		// Find where the word starts
		int wStart;

		for (wStart = pos; wStart >= 0; wStart--) {
			if (Character.isWhitespace(content.charAt(wStart))
					|| content.charAt(wStart) == '\n') {
				break;
			}
		}
		String word = content.substring(wStart + 1);

		mode = Mode.COLORATION;
		SwingUtilities.invokeLater(new ColorationTask(word, wStart, pos + 1));

	}

	private class ColorationTask implements Runnable {

		private String word;
		private int start;
		private int end;

		ColorationTask(String word, int start, int end) {
			this.word = word;
			this.start = start;
			this.end = end;

		}

		@Override
		public void run() {
			UspeedHighlighter uh = new UspeedHighlighter();
			// uh.highlightWord(textPane.getStyledDocument(), word, start);
			uh.highlightWord(textPane.getStyledDocument(), word, start);
			mode = Mode.INSERT;
		}
	}
}
